<template>
  <div class="page-container">
    <h1 class="page-title">健康概览</h1>
    
    <!-- 用户信息卡片 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <div class="health-card">
          <div class="card-header">
            <h3>个人信息</h3>
            <el-button type="primary" size="small" @click="goToProfile">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
          </div>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="info-item">
                <div class="info-label">姓名</div>
                <div class="info-value">{{ userStore.realName || '-' }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="info-item">
                <div class="info-label">性别</div>
                <div class="info-value">{{ genderText }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="info-item">
                <div class="info-label">年龄</div>
                <div class="info-value">{{ age || '0' }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="info-item">
                <div class="info-label">今日BMI</div>
                <div class="info-value">{{ latestBMI || '暂无记录' }}</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-col>
    </el-row>
    
    <!-- 今日数据 -->
    <el-row :gutter="20" class="data-row">
      <el-col :span="8">
        <div class="health-card">
          <div class="card-header">
            <h3>今日健康数据</h3>
            <el-button type="primary" size="small" @click="goToHealth">
              <el-icon><Plus /></el-icon>记录
            </el-button>
          </div>
          <div class="today-data">
            <div class="data-item">
              <div class="data-label">体重</div>
              <div class="data-value">{{ todayHealth.weight ? `${todayHealth.weight} kg` : '-' }}</div>
            </div>
            <div class="data-item">
              <div class="data-label">睡眠时长</div>
              <div class="data-value">{{ todayHealth.sleepDuration ? `${todayHealth.sleepDuration} 小时` : '-' }}</div>
            </div>
            <div class="data-item">
              <div class="data-label">心情</div>
              <div class="data-value">{{ moodText }}</div>
            </div>
          </div>
        </div>
      </el-col>
      
      <el-col :span="8">
        <div class="health-card">
          <div class="card-header">
            <h3>今日饮食</h3>
            <el-button type="primary" size="small" @click="goToDiet">
              <el-icon><Plus /></el-icon>记录
            </el-button>
          </div>
          <div class="today-data">
            <div class="data-item">
              <div class="data-label">餐次</div>
              <div class="data-value">{{ todayDietCount }} 餐</div>
            </div>
            <div class="data-item">
              <div class="data-label">总热量</div>
              <div class="data-value">{{ todayDietCalories ? `${todayDietCalories} kcal` : '-' }}</div>
            </div>
            <div class="data-item">
              <div class="data-label">蛋白质</div>
              <div class="data-value">{{ todayDietProtein ? `${todayDietProtein} g` : '-' }}</div>
            </div>
          </div>
        </div>
      </el-col>
      
      <el-col :span="8">
        <div class="health-card">
          <div class="card-header">
            <h3>今日运动</h3>
            <el-button type="primary" size="small" @click="goToExercise">
              <el-icon><Plus /></el-icon>记录
            </el-button>
          </div>
          <div class="today-data">
            <div class="data-item">
              <div class="data-label">运动次数</div>
              <div class="data-value">{{ todayExerciseCount }} 次</div>
            </div>
            <div class="data-item">
              <div class="data-label">总时长</div>
              <div class="data-value">{{ todayExerciseDuration ? `${todayExerciseDuration} 分钟` : '-' }}</div>
            </div>
            <div class="data-item">
              <div class="data-label">消耗热量</div>
              <div class="data-value">{{ todayExerciseCalories ? `${todayExerciseCalories} kcal` : '-' }}</div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    
    <!-- AI规划 -->
    <el-row :gutter="20" class="data-row">
      <el-col :span="24">
        <div class="health-card">
          <el-collapse v-model="activeCollapse">
            <el-collapse-item name="aiAdvice">
              <template #title>
                <div class="collapse-title">
                  <h3>AI规划</h3>
                  <el-button type="primary" size="small" @click.stop="refreshAdvice" :loading="adviceLoading">
                    <el-icon><Refresh /></el-icon>刷新
                  </el-button>
                </div>
              </template>
              <div class="advice-content" v-if="aiAdvice">
                <div v-html="marked(todayHealth.suggest || '')"></div>
              </div>
              <div class="empty-state" v-else>
                <el-icon class="empty-icon"><ChatDotRound /></el-icon>
                <p>暂无AI规划，请先记录今日健康数据</p>
                <el-button type="primary" @click="goToHealth">记录健康数据</el-button>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Edit, Plus, Refresh, ChatDotRound } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { useHealthStore } from '@/store/health'
import { useDietStore } from '@/store/diet'
import { useExerciseStore } from '@/store/exercise'
import { healthApi } from '@/api'
import dayjs from 'dayjs'
import { marked } from 'marked'

const router = useRouter()
const userStore = useUserStore()
const healthStore = useHealthStore()
const dietStore = useDietStore()
const exerciseStore = useExerciseStore()

const todayHealth = ref({})
const todayDietRecords = ref([])
const todayExerciseRecords = ref([])
const aiAdvice = ref('')
const adviceLoading = ref(false)
const activeCollapse = ref([]) // 控制折叠面板的展开状态，默认为空数组表示全部折叠

// 计算属性
const genderText = computed(() => {
  const genderMap = { 0: '未知', 1: '男', 2: '女' }
  return genderMap[userStore.gender] || '未知'
})

const age = computed(() => {
  if (!userStore.birthDate) return null
  const birthYear = dayjs(userStore.birthDate).year()
  return 2025 - birthYear
  
})

const latestBMI = computed(() => {
  // 如果有今日健康数据且有BMI，直接返回
  if (todayHealth.value.bmi) return todayHealth.value.bmi
  
  // 否则从最近的记录中查找
  if (healthStore.dailyRecords.length > 0) {
    const recordWithBMI = healthStore.dailyRecords.find(record => record.bmi)
    return recordWithBMI ? recordWithBMI.bmi : null
  }
  
  return null
})

const moodText = computed(() => {
  const moodMap = { 1: '极差', 2: '差', 3: '一般', 4: '好', 5: '极好' }
  return moodMap[todayHealth.value.mood] || '-'
})

const todayDietCount = computed(() => todayDietRecords.value.length)

const todayDietCalories = computed(() => {
  if (todayDietRecords.value.length === 0) return 0
  return todayDietRecords.value.reduce((sum, record) => sum + (record.calorie || 0), 0)
})

const todayDietProtein = computed(() => {
  if (todayDietRecords.value.length === 0) return 0
  return todayDietRecords.value.reduce((sum, record) => sum + (record.protein || 0), 0)
})

const todayExerciseCount = computed(() => todayExerciseRecords.value.length)

const todayExerciseDuration = computed(() => {
  if (todayExerciseRecords.value.length === 0) return 0
  return todayExerciseRecords.value.reduce((sum, record) => sum + (record.duration || 0), 0)
})

const todayExerciseCalories = computed(() => {
  if (todayExerciseRecords.value.length === 0) return 0
  return todayExerciseRecords.value.reduce((sum, record) => sum + (record.calorieConsume || 0), 0)
})

// 方法
const goToProfile = () => {
  router.push('/profile')
}

const goToHealth = () => {
  router.push('/health')
}

const goToDiet = () => {
  router.push('/diet')
}

const goToExercise = () => {
  router.push('/exercise')
}

const loadTodayData = async () => {
  const today = dayjs().format('YYYY-MM-DD')
  
  try {
    // 加载今日健康数据
    const healthResponse = await healthStore.getRecord(today)
    todayHealth.value = healthResponse || {}
    
    // 加载今日饮食记录
    const dietResponse = await dietStore.getRecords(today)
    todayDietRecords.value = dietResponse || []
    
    // 加载今日运动记录
    const exerciseResponse = await exerciseStore.getRecords(today)
    todayExerciseRecords.value = exerciseResponse || []
    
    console.log('今日饮食记录:', todayDietRecords.value)
    console.log('今日运动记录:', todayExerciseRecords.value)
  } catch (error) {
    console.error('加载今日数据失败', error)
  }
}

const refreshAdvice = async () => {
  if (!todayHealth.value.recordId) {
    return
  }
  
  adviceLoading.value = true
  try {
    const response = await healthApi.getAdvice({
      adviceType: 'daily',
      timeRange: 'today'
    })
    aiAdvice.value = response
  } catch (error) {
    console.error('获取AI建议失败', error)
  } finally {
    adviceLoading.value = false
  }
}

// 生命周期
onMounted(async () => {
  // 确保获取用户信息
  if (userStore.isLoggedIn && !userStore.realName) {
    try {
      await userStore.getUserInfo()
    } catch (error) {
      console.error('获取用户信息失败', error)
    }
  }
  
  await loadTodayData()
  
  // 如果有今日健康数据，自动获取AI建议
  if (todayHealth.value.recordId) {
    refreshAdvice()
  }
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background: var(--gradient-bg);
  min-height: calc(100vh - 80px);
}

.page-title {
  margin: 0 0 25px 0;
  color: var(--text-primary);
  font-size: 28px;
  font-weight: 700;
  position: relative;
  padding-bottom: 10px;
}

.page-title::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 80px;
  height: 3px;
  background: var(--gradient-primary);
  border-radius: var(--radius-sm);
}

.health-card {
  background: var(--gradient-card);
  border-radius: var(--radius-lg);
  padding: 25px;
  box-shadow: var(--shadow-md);
  border: 1px solid var(--border-light);
  transition: var(--transition-normal);
}

.health-card:hover {
  transform: translateY(-3px);
  box-shadow: var(--shadow-lg);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid var(--border-light);
}

.card-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
}

.collapse-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding-right: 20px;
}

.collapse-title h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
  display: flex;
  align-items: center;
}

.collapse-title h3 .el-icon {
  margin-right: 10px;
  color: var(--ai-color);
}

.info-item, .data-item {
  margin-bottom: 16px;
  padding: 15px;
  background: var(--bg-secondary);
  border-radius: var(--radius-md);
  transition: var(--transition-normal);
  border: 1px solid var(--border-light);
}

.info-item:hover, .data-item:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
  border-color: var(--primary-color);
}

.info-label, .data-label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: 8px;
  font-weight: 500;
}

.info-value, .data-value {
  font-size: 18px;
  color: var(--text-primary);
  font-weight: 600;
}

.data-row {
  margin-top: 25px;
}

.today-data {
  padding: 10px 0;
}

.advice-content {
  padding: 20px;
  background: var(--bg-secondary);
  border-radius: var(--radius-md);
  line-height: 1.6;
  color: var(--text-secondary);
  border: 1px solid var(--border-light);
}

/* Markdown样式 */
.advice-content :deep(h1) {
  font-size: 1.5em;
  font-weight: bold;
  margin: 0.5em 0;
  color: var(--text-primary);
}

.advice-content :deep(h2) {
  font-size: 1.3em;
  font-weight: bold;
  margin: 0.5em 0;
  color: var(--text-primary);
}

.advice-content :deep(h3) {
  font-size: 1.1em;
  font-weight: bold;
  margin: 0.5em 0;
  color: var(--text-primary);
}

.advice-content :deep(p) {
  margin: 0.5em 0;
}

.advice-content :deep(ul) {
  padding-left: 20px;
  margin: 0.5em 0;
}

.advice-content :deep(ol) {
  padding-left: 20px;
  margin: 0.5em 0;
}

.advice-content :deep(li) {
  margin: 0.3em 0;
}

.advice-content :deep(code) {
  background-color: var(--bg-tertiary);
  padding: 2px 6px;
  border-radius: var(--radius-sm);
  font-family: monospace;
  color: var(--primary-color);
}

.advice-content :deep(pre) {
  background-color: var(--bg-tertiary);
  padding: 15px;
  border-radius: var(--radius-md);
  overflow-x: auto;
  border: 1px solid var(--border-light);
}

.advice-content :deep(blockquote) {
  border-left: 4px solid var(--primary-color);
  padding-left: 15px;
  margin: 0.5em 0;
  color: var(--text-secondary);
}

.advice-content :deep(strong) {
  font-weight: bold;
  color: var(--text-primary);
}

.advice-content :deep(em) {
  font-style: italic;
}

/* 折叠面板样式 */
.health-card :deep(.el-collapse) {
  border: none;
}

.health-card :deep(.el-collapse-item__header) {
  border-bottom: none;
  background-color: transparent;
  padding: 0;
  height: auto;
  line-height: normal;
  transition: var(--transition-normal);
}

.health-card :deep(.el-collapse-item__header:hover) {
  color: var(--primary-color);
}

.health-card :deep(.el-collapse-item__wrap) {
  border-bottom: none;
}

.health-card :deep(.el-collapse-item__content) {
  padding: 0;
  padding-top: 20px;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: var(--text-secondary);
}

.empty-state .el-icon {
  font-size: 64px;
  margin-bottom: 15px;
  color: var(--text-disabled);
}

.empty-state p {
  font-size: 16px;
  margin: 0 0 20px 0;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .page-title {
    font-size: 24px;
  }
}

@media (max-width: 768px) {
  .page-container {
    padding: 15px;
  }
  
  .health-card {
    padding: 20px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .page-title {
    font-size: 22px;
  }
}
</style>